package com.fosun.spr.core.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.fosun.spr.core.constants.BaseConstants;

 
/**
 * 
 * @author zhangcheng
 * 
 */
public class ExtXmlUtils {

	/**
	 * JavaBean转换成xml 默认编码UTF-8
	 * 
	 * @param obj
	 * @param writer
	 * @return
	 */
	public static String convertToXml(Object obj) {
		return convertToXml(obj, BaseConstants.UTF_8);
	}

	/**
	 * JavaBean转换成xml
	 * 
	 * @param obj
	 * @param encoding
	 * @return
	 */
	public static String convertToXml(Object obj, String encoding) {
		String result = null;
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

			StringWriter writer = new StringWriter();
			marshaller.marshal(obj, writer);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	public static <T> T converyToJavaBean(String xml, Class<T> c) {
		T t = null;
		try {
			JAXBContext context = JAXBContext.newInstance(c);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			t = (T) unmarshaller.unmarshal(new StringReader(xml));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return t;
	}

	@SuppressWarnings("unchecked")
	public static <T> T converyToBeanObject(Object xml, Class<T> c) {
		String xmlStr = readFileContent(xml);
		T t = null;
		try {
			JAXBContext context = JAXBContext.newInstance(c);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			t = (T) unmarshaller.unmarshal(new StringReader(xmlStr));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return t;
	}

	/**
	 * 
	 * @Title: readFileContent
	 * @Description: fileObj 可以是一个File，也可以是一个file路径
	 * @param fileObj
	 * @throws IOException
	 * @return String
	 */
	public static String readFileContent(Object fileObj) {

		File file = null;

		try {

			if (fileObj instanceof File) {
				file = (File) fileObj;
			} else {
				file = new File((String) fileObj);
			}

			BufferedReader bf = new BufferedReader(new FileReader(file));

			String content = "";
			StringBuilder sb = new StringBuilder();

			while (content != null) {
				content = bf.readLine();

				if (content == null) {
					break;
				}

				sb.append(content.trim());
			}

			bf.close();
			return sb.toString();
		} catch (IOException ie) {
			ie.printStackTrace();
		}
		return "";
	}
}
